<template>
  <el-dialog
    v-model="dialogVisible"
    title="批量创建敏感词"
    width="600px"
    :before-close="handleClose"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="敏感词列表" prop="words" required>
        <el-input
          v-model="formData.wordsText"
          type="textarea"
          :rows="8"
          placeholder="请输入敏感词，每行一个&#10;例如：&#10;敏感词1&#10;敏感词2&#10;敏感词3"
          @input="handleWordsChange"
        />
        <div class="word-count">共 {{ formData.words.length }} 个敏感词</div>
      </el-form-item>

      <el-form-item label="敏感词类型" prop="type" required>
        <el-select
          v-model="formData.type"
          placeholder="选择敏感词类型"
          style="width: 100%"
        >
          <el-option
            v-for="type in sensitiveWordTypes"
            :key="type.value"
            :label="type.label"
            :value="type.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="严重程度" prop="severity" required>
        <el-select
          v-model="formData.severity"
          placeholder="选择严重程度"
          style="width: 100%"
        >
          <el-option
            v-for="severity in severityLevels"
            :key="severity.value"
            :label="severity.label"
            :value="severity.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="过滤模式" prop="filterMode" required>
        <el-select
          v-model="formData.filterMode"
          placeholder="选择过滤模式"
          style="width: 100%"
          @change="handleFilterModeChange"
        >
          <el-option
            v-for="mode in filterModes"
            :key="mode.value"
            :label="mode.label"
            :value="mode.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        v-if="formData.filterMode === 'REPLACE'"
        label="替换文本"
        prop="replacement"
      >
        <el-input
          v-model="formData.replacement"
          placeholder="请输入替换文本，默认为 ***"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="描述信息" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入描述信息（可选）"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="分类标签" prop="tags">
        <el-select
          v-model="formData.tags"
          multiple
          filterable
          allow-create
          placeholder="请选择或输入标签"
          style="width: 100%"
        >
          <el-option
            v-for="tag in commonTags"
            :key="tag"
            :label="tag"
            :value="tag"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :value="1">启用</el-radio>
          <el-radio :value="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="覆盖设置" prop="overwrite">
        <el-checkbox v-model="formData.overwrite">
          覆盖已存在的敏感词
        </el-checkbox>
        <div class="form-tip">
          勾选后，如果敏感词已存在，将使用新的配置覆盖原有设置
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          批量创建
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules
} from "element-plus";
import {
  batchCreateSensitiveWordsApi,
  SensitiveWordType,
  SeverityLevel,
  FilterMode,
  type BatchCreateSensitiveWordsParams,
  type BatchCreateResult,
  SensitiveWordManagementUtils
} from "@/api/sensitive-word-management";

// Props
interface Props {
  visible: boolean;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  "update:visible": [value: boolean];
  success: [result: BatchCreateResult];
}>();

// 响应式数据
const dialogVisible = computed({
  get: () => props.visible,
  set: value => emit("update:visible", value)
});

const formRef = ref<FormInstance>();
const loading = ref(false);

// 表单数据
const formData = reactive({
  wordsText: "",
  words: [] as string[],
  type: SensitiveWordType.PROFANITY,
  severity: SeverityLevel.MEDIUM,
  filterMode: FilterMode.REPLACE,
  replacement: "***",
  description: "",
  tags: [] as string[],
  status: 1,
  overwrite: false
});

// 选项数据
const sensitiveWordTypes = [
  { label: "脏话", value: SensitiveWordType.PROFANITY },
  { label: "政治敏感", value: SensitiveWordType.POLITICS },
  { label: "广告", value: SensitiveWordType.ADVERTISEMENT },
  { label: "暴力内容", value: SensitiveWordType.VIOLENCE },
  { label: "违法内容", value: SensitiveWordType.ILLEGAL },
  { label: "垃圾信息", value: SensitiveWordType.SPAM }
];

const severityLevels = [
  { label: "轻微", value: SeverityLevel.LIGHT },
  { label: "一般", value: SeverityLevel.NORMAL },
  { label: "中等", value: SeverityLevel.MEDIUM },
  { label: "严重", value: SeverityLevel.SERIOUS },
  { label: "极严重", value: SeverityLevel.CRITICAL }
];

const filterModes = [
  { label: "替换模式", value: FilterMode.REPLACE },
  { label: "拦截模式", value: FilterMode.BLOCK }
];

const commonTags = ["批量", "导入", "测试", "系统", "用户举报", "自动检测"];

// 表单验证规则
const rules: FormRules = {
  words: [{ required: true, message: "请输入敏感词", trigger: "blur" }],
  type: [{ required: true, message: "请选择敏感词类型", trigger: "change" }],
  severity: [{ required: true, message: "请选择严重程度", trigger: "change" }],
  filterMode: [{ required: true, message: "请选择过滤模式", trigger: "change" }]
};

// 处理敏感词文本变化
const handleWordsChange = () => {
  const words = formData.wordsText
    .split("\n")
    .map(word => word.trim())
    .filter(word => word.length > 0);
  formData.words = [...new Set(words)]; // 去重
};

// 处理过滤模式变化
const handleFilterModeChange = () => {
  if (formData.filterMode === FilterMode.BLOCK) {
    formData.replacement = "";
  } else {
    formData.replacement = "***";
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    if (formData.words.length === 0) {
      ElMessage.warning("请输入至少一个敏感词");
      return;
    }

    loading.value = true;

    const params: BatchCreateSensitiveWordsParams = {
      words: formData.words,
      type: formData.type,
      severity: formData.severity,
      filterMode: formData.filterMode,
      replacement: formData.replacement || undefined,
      description: formData.description || undefined,
      tags: formData.tags.length > 0 ? formData.tags : undefined,
      status: formData.status,
      overwrite: formData.overwrite
    };

    const response = await batchCreateSensitiveWordsApi(params);

    if (response.code === 200) {
      const result = response.data;

      // 显示结果
      let message = `批量创建完成！\n`;
      message += `成功: ${result.successCount} 个\n`;
      if (result.failedCount > 0) {
        message += `失败: ${result.failedCount} 个\n`;
      }
      if (result.existingCount > 0) {
        message += `已存在: ${result.existingCount} 个`;
      }

      await ElMessageBox.alert(message, "批量创建结果", {
        confirmButtonText: "确定",
        type: "success"
      });

      emit("success", result);
      handleClose();
    } else {
      ElMessage.error(response.message || "批量创建失败");
    }
  } catch (error) {
    console.error("批量创建失败:", error);
    ElMessage.error("批量创建失败");
  } finally {
    loading.value = false;
  }
};

// 关闭对话框
const handleClose = () => {
  // 重置表单
  formData.wordsText = "";
  formData.words = [];
  formData.type = SensitiveWordType.PROFANITY;
  formData.severity = SeverityLevel.MEDIUM;
  formData.filterMode = FilterMode.REPLACE;
  formData.replacement = "***";
  formData.description = "";
  formData.tags = [];
  formData.status = 1;
  formData.overwrite = false;

  if (formRef.value) {
    formRef.value.clearValidate();
  }

  dialogVisible.value = false;
};
</script>

<style scoped>
.word-count {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}

.form-tip {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
}

.dialog-footer {
  text-align: right;
}
</style>
